package com.microtf.inscription.web.controller;


import com.microtf.inscription.framework.service.BaseService;
import com.microtf.inscription.framework.service.UserService;
import com.microtf.inscription.framework.vo.user.UserLoginDto;
import com.microtf.inscription.jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;


/**
 * 服务基础类
 *
 * @author guliuzhong
 */
public class BaseController extends BaseService {

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取当前已经登录用户
     * 未登录时用户为空
     *
     * @return 已经登录的用户信息
     */
    public Optional<User> getLoginUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            return Optional.empty();
        }
        UserLoginDto principal = (UserLoginDto) authentication.getPrincipal();
        User user = userService.getUser(principal.getUsername());
        return Optional.ofNullable(user);
    }
}
